﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Core.ProxyService;
using System.Linq;
using System.Collections.Generic;
using System.Xml;
using System.ServiceModel.Syndication;
using System.IO;
using System.Threading;
using Api.Model;
using Api.Model;

using Articles = System.Collections.Generic.IEnumerable<Api.Model.Article>;

namespace RssProxyService
{
    public class RssProxyService : NotPaginatedProxyService
    {
        private string uri;
        private Func<WebClient> webClientFactory;
        private IRssMapper rssMapper;

        public RssProxyService(Func<WebClient> webClientFactory, string uri, IRssMapper rssMapper)
        {
            this.webClientFactory = webClientFactory;
            this.uri = uri;
            this.rssMapper = rssMapper;
        }

        public override void GetArticlesAsync(Action<ArticlesDownloadedEventArgs> callback)
        {
            base.GetArticlesAsync(callback);

            var webClient = this.webClientFactory();

            DownloadStringCompletedEventHandler handler = null;

            handler = (s, e) =>
                {
                    HandleResponse(callback, e);
                    webClient.DownloadStringCompleted -= handler;
                };

            webClient.DownloadStringCompleted += handler;
            webClient.DownloadStringAsync(new Uri(this.uri, UriKind.Absolute));
        }

        private void HandleResponse(Action<ArticlesDownloadedEventArgs> callback, DownloadStringCompletedEventArgs e)
        {
            ArticlesDownloadedEventArgs args;

            if (e.Error == null && !e.Cancelled)
            {
                try 
                {
                    var articles = rssMapper.GetMappedItems(e.Result);
                    args = new ArticlesDownloadedEventArgs(null, false, e.UserState, articles);
                }
                catch(Exception ex)
                {
                    args = new ArticlesDownloadedEventArgs(ex, e.Cancelled, e.UserState, null);
                }  
            }
            else 
            {
                args = new ArticlesDownloadedEventArgs(e.Error, e.Cancelled, e.UserState, null);
            }

            callback(args);    
        }
    }
}
